/**
 * 
 */
package info.niwota.ezb;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;

/**
 * @author qiangli
 * 
 */
public class ScreenService extends Service {
	private static final String TAG = "ScreenService";

	public class LocalBinder extends Binder {
		ScreenService getService() {
			return ScreenService.this;
		}
	}

	private final IBinder binder = new LocalBinder();

	@Override
	public IBinder onBind(Intent i) {
		return binder;
	}

	private IntentFilter intentFilter;

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		
		private String state = null;
		
		private long offtime = 0;

		private final long MIN_ELAPSE = 1000;
		
		public void onReceive(Context ctx, Intent intent) {
			final String action = intent.getAction();

			if (Debug.DEBUG) {
				Log.d(TAG, "action: " + action + " phone state: " + state);
			}
			
			if (PhoneUtil.ACTION_PHONE_STATE.equals(action)) {
				state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
				
				if (Debug.DEBUG) {
					Log.d(TAG, "phone state change, state: " + state + " extras: " + intent.getExtras());
				}
				
				if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
					//set by ImageHolderActivity
					final boolean active = ApplicationContext.isActive();
					if (Debug.DEBUG) {
						Log.d(TAG,
								"phone state change,  state: "
										+ state + " active: " + active);
					}
					
					KeyguardUtil.enableGuard();
					//
					if (active) {
						if (Preferences.getRunningStatus(ctx)) {
							KeyguardUtil.disableGuard(ScreenService.this);
							ImageHolderActivity.ensureRunning(ctx);
						}
					}
					//reset
					state = null;
					ApplicationContext.setActive(false);
				}
				
				return;
			}
			
			if (Intent.ACTION_SCREEN_OFF.equals(action)) {
				KeyguardUtil.enableGuard();
				
				offtime = System.currentTimeMillis();
				return;
			}
			
			if (Intent.ACTION_SCREEN_ON.equals(action)) {
				//ignore if incoming call
				if (state != null) {
					if (Debug.DEBUG) {
						Log.d(TAG, "on a call now, ignore action: " + action + " phone state: " + state);
					}
					return;
				}
				
				//ignore on immediately following off
				long elapse = System.currentTimeMillis() - offtime;
				
				if (Debug.DEBUG) {
					Log.d(TAG, "Elapsed: "+ elapse + " ignore action: " + action + " phone state: " + state);
				}
				if (elapse < MIN_ELAPSE) {
					if (Debug.DEBUG) {
						Log.d(TAG, "too soon: "+ elapse + " ignore action: " + action + " phone state: " + state);
					}
					return;
				}
				
				if (Preferences.getRunningStatus(ctx)) {
					KeyguardUtil.disableGuard(ScreenService.this);
					ImageHolderActivity.ensureRunning(ctx);
				}
			}
		}
	};

	@Override
	public void onCreate() {
		super.onCreate();

		if (Debug.DEBUG) {
			Log.d(TAG, "onCreate");
		}

		// screen action for key guard
		try {
			if (Debug.DEBUG) {
				Log.d(TAG, "receiver: " + receiver);
			}

			intentFilter = new IntentFilter();
			intentFilter.addAction(Intent.ACTION_SCREEN_ON);
			intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
			intentFilter.addAction(PhoneUtil.ACTION_PHONE_STATE);

			registerReceiver(receiver, intentFilter);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroy() {
		if (Debug.DEBUG) {
			Log.d(TAG, "onDestroy");
		}

		try {
			unregisterReceiver(receiver);
		} catch (Exception e) {
			e.printStackTrace();
		}
		receiver = null;

		//
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		handleCommand(intent);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		handleCommand(intent);
		return START_STICKY;
	}

	private void handleCommand(Intent intent) {
		if (Debug.DEBUG) {
			Log.d(TAG, "handleCommand intent: " + intent);
		}
		//
	}

	public static void shutdown(Context ctx) {
		Intent intent = new Intent(ctx, ScreenService.class);
		try {
			ctx.stopService(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void startup(Context ctx) {
		Intent intent = new Intent(ctx, ScreenService.class);
		try {
			ctx.startService(intent);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
